package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Entity.FanSwitchBean;
import com.huaxin.common.message.view.CircleImageView;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.HttpCommit;
import com.huaxin.hxcloud.find.view.RefreshDataEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by hebing on 2017/5/17.
 */

public class FanSwitchActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.activity_fan_xrv)
    XRefreshView xRefreshView;
    @BindView(R.id.activity_fan_rv)
    RecyclerView recyclerView;
    private FanAdapter mFanAdapter;
    private boolean flags = true;

    public static final int TYPE_REFRESH = 1;
    public static final int TYPE_MORE    = 0;
    List<FanSwitchBean.UserArrayBean> userArray = new ArrayList<>();
    public static int pageNum = 0;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_fanswitch;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        toolbar.setTitle("关注");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setPullRefreshEnable(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mFanAdapter = new FanAdapter();
        recyclerView.setAdapter(mFanAdapter);
        //
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                super.onRefresh(isPullDown);
                pageNum = 0;
                ApiRequsetData(TYPE_REFRESH, 0);
            }

            @Override
            public void onLoadMore(final boolean isSilence) {
                super.onLoadMore(isSilence);
                pageNum++;
                ApiRequsetData(TYPE_MORE, pageNum);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        ApiRequsetData(TYPE_REFRESH, 0);
        refreshDatas(TYPE_REFRESH);
        flags = false;
    }

    private void refreshDatas(int loadtype) {
        if (loadtype == TYPE_REFRESH) {
            mFanAdapter.setDatas(userArray);
        } else if (loadtype == TYPE_MORE) {
            mFanAdapter.getDatas().addAll(userArray);
        }
        mFanAdapter.notifyDataSetChanged();
    }


    class FanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        public static final int TYPE_CONTENT = 1;
        public static final int TYPE_FOOTER  = 0;

        protected List<FanSwitchBean.UserArrayBean> datas = new ArrayList();

        public List<FanSwitchBean.UserArrayBean> getDatas() {
            if (datas == null)
                datas = new ArrayList();
            return datas;
        }

        public void setDatas(List<FanSwitchBean.UserArrayBean> datas) {
            this.datas = datas;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_FOOTER) {
                return new FanFooter(LayoutInflater.from(FanSwitchActivity.this).inflate(R.layout.fanswitch_footer_item, parent, false));
            } else {
                return new FanHolder(LayoutInflater.from(FanSwitchActivity.this).inflate(R.layout.fanswitch_rv_item, parent, false));
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == TYPE_FOOTER) {
                FanFooter fanFooter = (FanFooter) holder;
                if (datas.size() == 0) {
                    fanFooter.textView.setVisibility(View.VISIBLE);
                } else {
                    fanFooter.textView.setVisibility(View.GONE);
                }
            } else {
                FanHolder fanHolder = (FanHolder) holder;
                final FanSwitchBean.UserArrayBean userArrayBean = datas.get(position);
                //
                if ("".equals(userArrayBean.getCompany())) {

                } else {
                    fanHolder.textCom.setText(userArrayBean.getCompany());
                }
                HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
                instance.setHeadImage(FanSwitchActivity.this, userArrayBean.getImg(), userArrayBean.getNickName(), fanHolder.circleImageView);
                fanHolder.textName.setText(userArrayBean.getNickName());
                fanHolder.textFan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < datas.size(); i++) {
                            int id = datas.get(i).getId();
                            if (userArrayBean.getId() == id) {
                                datas.remove(i);
                            }
                        }
                        HttpCommit httpCommit = new HttpCommit();
                        httpCommit.commitFan(userArrayBean.getId());
                        notifyDataSetChanged();
                        //LocalBroadcastManager.getInstance(FanSwitchActivity.this).sendBroadcast(new Intent(ListFragment.LOCALRECEIVER));
                        EventBus.getDefault().post(new RefreshDataEvent(true));
                    }
                });
                fanHolder.layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(FanSwitchActivity.this, FanUserInfoActivity.class);
                        intent.putExtra("userId", userArrayBean.getId());
                        startActivity(intent);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return datas.size() + 1;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == getItemCount() - 1) {
                return TYPE_FOOTER;
            }
            return TYPE_CONTENT;
        }
    }

    class FanHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.fan_icon)
        AvatarImageView circleImageView;
        @BindView(R.id.fan_niceName)
        TextView        textName;
        @BindView(R.id.fan_company)
        TextView        textCom;
        @BindView(R.id.fan_fan)
        TextView        textFan;
        @BindView(R.id.fan_ll)
        LinearLayout    layout;

        public FanHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class FanFooter extends RecyclerView.ViewHolder {
        @BindView(R.id.fan_switch_footer)
        LinearLayout textView;

        public FanFooter(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private void ApiRequsetData(final int type, int pageNum) {
        if (flags) {
            updateLoadStatus(LOADING);
        }
        Call<FanSwitchBean> call = getRequestApi().requestFanBean(pageNum);
        autoClose(call);
        call.enqueue(new Callback<FanSwitchBean>() {
            @Override
            public void onResponse(Call<FanSwitchBean> call, Response<FanSwitchBean> response) {

                if (response.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                    FanSwitchBean body = response.body();
                    if ("success".equals(body.getMsg())) {
                        userArray = body.getUserArray();
                        if (userArray.size() != 0) {
                            if (type == TYPE_REFRESH) {
                                refreshDatas(TYPE_REFRESH);
                                xRefreshView.stopRefresh();
                            } else {
                                refreshDatas(TYPE_MORE);
                                xRefreshView.stopLoadMore();
                            }
                        } else {
                            if (type == TYPE_REFRESH) {
                                xRefreshView.stopRefresh();
                                updateLoadStatus(LOAD_NO_DATA);
                                return;
                            } else {
                                xRefreshView.stopLoadMore();
                                ToastUtil.showToastShort("没有更多");
                            }
                        }
                    } else {
                        ToastUtil.showToastShort("数据异常");
                        xRefreshView.stopRefresh();
                        xRefreshView.stopLoadMore();
                    }
                }
            }

            @Override
            public void onFailure(Call<FanSwitchBean> call, Throwable t) {
                ToastUtil.showToastShort("网络异常");
                updateLoadStatus(LOAD_SUCCESS);
            }
        });
    }

}
